﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace YoProgramo.Infrastructure.Tools.PagedList
{
    public static class PagedListExtensions
    {
        public static IPagedList<T> ToPagedList<T>(this IEnumerable<T> superset, int index, int pageSize)
        {
            return new PagedList<T>(superset, index, pageSize);
        }

        public static string Paging<T>(this HtmlHelper html, IPagedList<T> pagedList,
                                       string url, string pagePlaceHolder) {

            StringBuilder sb = new StringBuilder();

            if (pagedList.TotalItemCount > pagedList.PageSize) {

                sb.Append("<ul class=\"paging\">");

                if (pagedList.HasPreviousPage) { // previous link
                    sb.Append("<li class=\"paginglinksw\"><a href=\"");
                    sb.Append(url.Replace(pagePlaceHolder, (pagedList.PageIndex - 1).ToString()));
                    sb.Append("\" title=\"Atras\">Atras</a></li>");
                }

                for (int i = 0; i < pagedList.PageCount; i++) {
                    sb.Append("<li>");
                    if (i == pagedList.PageIndex) {
                        sb.Append((i).ToString());
                    } else {
                        sb.Append("<a href=\"");
                        sb.Append(url.Replace(pagePlaceHolder, (i).ToString()));
                        sb.Append("\" title=\"Go to Page ").Append((i).ToString());
                        sb.Append("\">").Append((i).ToString()).Append("</a>");
                    }
                    sb.Append("</li>");
                }

                if (pagedList.HasNextPage) { // next link
                    sb.Append("<li class=\"paginglinksw\"><a href=\"");
                    sb.Append(url.Replace(pagePlaceHolder, (pagedList.PageIndex + 1).ToString()));
                    sb.Append("\" title=\"Próxima página\">Próxima</a></li>");
                }

                sb.Append("</ul>");
            }

            return sb.ToString();
                                       }

    }
}